<template>
    <el-dialog
        v-model="dialogVisible"
        :title="pageTitle"
        width="70%"
        :before-close="handleClose"
    >
        <el-form ref="queryRef" :inline="true">
            <el-form-item label="绩效考核名称" prop="date">
                <el-input placeholder="请输入绩效考核名称" v-model="kpiName" :disabled="disabled"></el-input>
            </el-form-item>
        </el-form>
        <div class="box">
            <el-row :gutter="20">
                <el-col :span="12">
                    <div class="title">指标库</div>
                    <el-button type="primary" @click="handleQuery" style="margin-bottom:10px" :disabled="disabled">新增指标</el-button>
                    <div class="">
                        <el-table
                        border
                        :data="targetList"
                        ref="tableRef"
                        height="500"
                        row-key="indicatorsId"
                        @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="55" :selectable="selectable" />
                            <el-table-column prop="name" label="指标名称" align="center"></el-table-column>
                            <el-table-column prop="targetVal" label="目标值" width="120" align="center">
                                <template #default="scope">
                                    <el-input
                                    v-model.number="scope.row['targetVal']"
                                    type="number"
                                    @keydown="inputLimit"
                                    placeholder="0.00"
                                    :disabled="disabled"
                                    >
                                    </el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="weightsVal" label="权重值" width="120" align="center">
                                <template #default="scope">
                                    <el-input
                                    v-model.number="scope.row['weightsVal']"
                                    type="number"
                                    @keydown="inputLimit"
                                    placeholder="0~100"
                                    :disabled="disabled"
                                    >
                                    </el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="weight" label="操作" width="100" align="center">
                                <template #default="scope">
                                    <el-button link type="primary" size="small" :disabled="disabled" @click="editData(scope)">修改</el-button>
                                    <el-popconfirm
                                        confirm-button-text="删除"
                                        cancel-button-text="取消"
                                        icon-color="#626AEF"
                                        title="确认删除?"
                                        @confirm="confirmEvent(scope.row.id)"
                                    >
                                        <template #reference>
                                            <el-button link type="danger" :disabled="disabled" size="small">删除</el-button>
                                        </template>
                                    </el-popconfirm>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="title">人员库</div>
                    <div class="head-container">
                    <el-input
                        v-model="deptName"
                        placeholder="请输入部门名称"
                        clearable
                        prefix-icon="Search"
                        style="margin-bottom: 20px"
                        :disabled="disabled"
                    />
                    </div>
                    <div class="head-container">
                    <!-- <el-tree
                        :data="deptOptions"
                        :props="{ label: 'label', children: 'children' }"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        
                        highlight-current
                        default-expand-all
                        @node-click="handleNodeClick"
                    /> -->
                    </div>
                    <el-tree
                        style="max-width: 600px"
                        :props="{
                            label: 'label',
                            children: 'children',
                        }"
                        :data="deptOptions"
                        :filter-node-method="filterNode"
                        show-checkbox
                        ref="deptTreeRef"
                        node-key="id"
                        :default-expanded-keys="userIds"
                        :default-checked-keys="userIds"
                        @check-change="handleCheckChange"
                        @node-click="handleNodeClick"
                    />
                </el-col>
            </el-row>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">关闭</el-button>
                <el-button v-if="props.pageState != '1'" type="primary" @click="submit">提交</el-button>
            </div>
        </template>
        <el-dialog
            v-model="innerVisible"
            width="500"
            :title="title"
            append-to-body
            >
            <el-input v-model="target.name" placeholder="请输入指标名称"></el-input>
            <template #footer>
            <div class="dialog-footer">
                <el-button @click="innerVisible=false">关闭</el-button>
                <el-button type="primary" @click="save">保存</el-button>
            </div>
        </template>
        </el-dialog>
    </el-dialog>
</template>
<script setup>
import { getUser, getIndicatorsList, updateTargetName, deleteTarget, addTarget, addTargetExamine, getDetailData, updateData } from "@/api/kpi/list";
const { proxy } = getCurrentInstance();
import { onMounted, toRaw, ref } from 'vue'


const emit = defineEmits(['submit', 'closeNew'])
const props = defineProps(['pageId','pageState'])
const dialogVisible = ref(true);
const innerVisible = ref(false);
const kpiName = ref('')
const deptName = ref("");
const title = ref("");
const target = ref({
    name: '',
    id: ''
});
const deptOptions = ref(undefined);
const targetList = ref([])
const multipleSelection = ref([])
const userIds = ref([]) // 当前选择的人员
const indicatorsList = ref([]) // 当前选择的指标
const pageTitle = ref("") // 页面名称,新增&查看&编辑
const selectedRows = ref([]) // 回显当前表格勾选的行
const tableRef = ref()
const disabled = ref(false)
const updateTargetNameTableColumn = ref(null) // 修改指标名当前的表格行下标

onMounted(() => {
    pageTitle.value = props.pageState == '0' ? '新增绩效考核' : props.pageState == '1' ? '查看绩效考核' : '编辑绩效考核'
    getDeptTree();
    getIndicatorsListData()
})

const selectable = (row, index) => {
    // 查看页面表格不可操作
    return props.pageState == '1' ? false : true 
}

// 查看和编辑时获取详情
function getDetail() {
    getDetailData(props.pageId).then(res=>{
        if(res.code == 200) {
            // 获取数状数据
            userIds.value = res.data.userIds;
            kpiName.value = res.data.name;
            // 回显勾选的行
            selectedRows.value = targetList.value.filter(item => 
                res.data.indicatorsList.some(row => row.indicatorsId == item.id)
            );
            selectedRows.value.forEach(item=>{
                tableRef.value.toggleRowSelection(item,true)
            })
            res.data.indicatorsList.forEach(d=>{
                targetList.value.forEach((v,i)=>{
                    if(d.indicatorsId == v.id) {
                        targetList.value[i].targetVal = d.targetVal;
                        targetList.value[i].weightsVal = d.weightsVal;
                    }
                })
            })
        }
    })
}

// 关闭
const handleClose = () => {
    dialogVisible.value = false;
    emit('closeNew', false)
}

// 校验目标值和权重值是否填写
function verification() {
    for(let i = 0; i < indicatorsList.value.length; i++) {
        if(!indicatorsList.value[i].targetVal || !indicatorsList.value[i].weightsVal) {
            return true;
        }
    }
}

// 新增指标
function handleQuery(){
    target.value.name = ''
    title.value = '新增指标';
    innerVisible.value = true;
}
// 修改指标
function editData (scope) {
    title.value = '编辑指标'
    innerVisible.value = true
    target.value.name = scope.row.name
    target.value.id = scope.row.id
    updateTargetNameTableColumn.value = scope.$index
}
// 修改指标名提交
function save() {
    if(title.value == '新增指标') {
        addTarget(
            {
                name: target.value.name
            }
        ).then(res=>{
            if(res.code == 200){
                innerVisible.value = false;
                target.value.name = '';
                getIndicatorsListData()
            }
        })
    } else if (title.value == '编辑指标') {
        updateTargetName(target.value).then(res=>{
            if(res.code == 200){
                targetList.value[updateTargetNameTableColumn.value].name = target.value.name
                innerVisible.value = false;
            }
        })
    }
}
// 删除指标
function confirmEvent (id) {
    deleteTarget(id).then(res=>{
        if(res.code == 200){
            ElMessage({
                message: '删除成功!',
                type: 'success',
                plain: true,
            })
            getIndicatorsListData()
        }
    })
}
// 获取指标列表
function getIndicatorsListData() {
    getIndicatorsList().then(res=>{
        if(res.code == 200){
            targetList.value = res.data;
            if(props.pageState == '1'){
                disabled.value = true
            }
            if(props.pageState == '1' || props.pageState == '2'){
                getDetail()
            }
        }
    })
}
// 新增弹框提交
function submit () {
    // 获取表格勾选的数据
    const selection = proxy.$refs['tableRef'].getSelectionRows();
    let indicatorsListArr = []
    if(selection.length) {
        toRaw(selection).forEach((v,i)=>{
            indicatorsListArr.push(toRaw(v))
            indicatorsListArr[i]['indicatorsId'] = toRaw(v).id
        })
    }
    indicatorsList.value = indicatorsListArr
    // 校验必填
    if (!kpiName.value) {
        ElMessage({
            message: '绩效考核名称必填!',
            type: 'warning',
            plain: true,
        })
        return
    } else if (!userIds.value.length) {
        ElMessage({
            message: '请选择人员!',
            type: 'warning',
            plain: true,
        })
        return
    } else if (!indicatorsList.value.length) {
        ElMessage({
            message: '请选择指标!',
            type: 'warning',
            plain: true,
        })
        return
    } else if (verification()) {
        ElMessage({
            message: '指标的目标值或权重值不能为空!',
            type: 'warning',
            plain: true,
        })
        return
    }
    let params = {
        "name": kpiName.value,
        "userIds": userIds.value,
        "indicatorsList": indicatorsList.value
    }
    if(props.pageState == '0'){
        addTargetExamine(params).then(res=>{
            if(res.code == 200) {
                ElMessage({
                    message: '提交成功!',
                    type: 'success',
                    plain: true,
                })
                dialogVisible.value = false;
                emit('submit')
            }
        })
    } else if (props.pageState == '2') {
        updateData({
            id: props.pageId,
            "name": kpiName.value,
            "userIds": userIds.value,
            "indicatorsList": indicatorsList.value
        }).then(res=>{
            if(res.code == 200) {
                ElMessage({
                    message: '提交成功!',
                    type: 'success',
                    plain: true,
                })
                dialogVisible.value = false;
                emit('submit')
            }
        })
    }
}
// 指标列表勾选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
// 节点选择事件
function handleCheckChange(data, checked, indeterminate) {
    const datas = proxy.$refs['deptTreeRef'].getCheckedNodes(false, false)
    let arr = []
    if(datas.length) {
        datas.forEach(v=>{
            // 1:用户
            if(v.isUserNode == 1) {
                arr.push(v.id)
            }
        })
        userIds.value = arr
    }
}
/** 节点单击事件 */
function handleNodeClick(data) {
    console.log(data)
};
/** 查询部门下拉树结构 */
function getDeptTree() {
    getUser().then(response => {
        if(response.data.length) {
            response.data = removeObjects(response.data)
            deptOptions.value = response.data
            // 查看页面时组件不可点击
            if(props.pageState == '1') {
                const arr = treeDisabled(response.data)
                console.log(arr)
            }
        }
    });
};
// 查看时不可勾选
function treeDisabled(data) {
    // debugger
    if(Array.isArray(data)) {
        return data.map(v=>{
            v['disabled'] = 'disabled';
            treeDisabled(v)
            return true
        })
    } else if (data.children) {
        return data.children.map(v=>{
            v['disabled'] = 'disabled';
            treeDisabled(v)
            return true
        })
    }
}
// 遍历树组件数据,清除isUserNode为0 且children为undefined
function removeObjects(obj) {
  if (Array.isArray(obj)) {
    return obj.filter(item => {
      if (item.isUserNode === 0 && item.children === undefined) {
        return false;
      }
      if (Array.isArray(item.children)) {
        item.children = removeObjects(item.children);
      }
      return true;
    });
  } else if (typeof obj === 'object' && obj!== null) {
    for (let key in obj) {
      if (obj[key] && typeof obj[key] === 'object') {
        obj[key] = removeObjects(obj[key]);
      }
    }
    return obj;
  } else {
    return obj;
  }
}
/** 根据名称筛选部门树 */
watch(deptName, val => {
    proxy.$refs["deptTreeRef"].filter(val);
});
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
};
function inputLimit (e) {
    let key = e.key
    // 不允许输入'e'和'+'、'-'、'Shift'
    if (['e', '+', '-', 'shift'].includes(key)) {
        e.returnValue = false
        return false
    }
    return true
}
</script>
<style lang="scss" scoped>
    ::v-deep .el-tree {
        height: 500px;
        overflow: auto;
    }
    .title {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 10px;
    }
</style>